import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {BaseComponent} from '../common/base.component';
import {FileUploader} from 'ng2-file-upload';
import {LogicAddService} from './logicAdd.service';
import {AddPlaceService} from '../place/place.service';
import {AddLogicInfo, PathInfo, RealInfoPage, AddEvent} from './logicAdd';
import {Headers, Http} from '@angular/http';
import {ParamConfig} from '../common/param.config';
import {UserService} from '../user/user.service';
import 'rxjs/add/operator/toPromise';

declare var $: any;

@Component({
  selector: 'app-logicadd',
  templateUrl: './logicAdd.component.html'
})
export class LogicAddComponent extends BaseComponent implements OnInit {
  uploader: FileUploader = new FileUploader({
    url: ParamConfig.HTTP_WEB_HOST_URL + 'rbFile/upload?type=0',
    method: 'POST',
    itemAlias: 'file'
  });
  public token: string;
  private hostUrlAddLogic = ParamConfig.HTTP_WEB_HOST_URL + 'logicNode/saveLogicNode'; // URL to web api
  curPage: Number = 1;
  mapId: string;
  id: string; // 路径Id
  private eventId: String = '';
  pathInfo: PathInfo[];
  realInfoPage: RealInfoPage;
  addEvent: AddEvent[];
  logic: [{}];
  path: [{}];
  map: string;
  fileId: string;
  imgUrl: string;
  curaddLogicInfo: AddLogicInfo;
  file: Array<Object>;

  constructor(private addPlaceService: AddPlaceService,
              private http: Http, private router: Router,
              private logicAddService: LogicAddService,
              private userService: UserService) {
    super();
  }

  ngOnInit() {
    this.token = this.userService.getToken();
    this.curaddLogicInfo = {
      name: '',
      realNodeId: '',
      type: '',
      pathId: '',
      fileId: '',
      sort: '',
      mapId: ''
    };
    this.searchPath();
    this.queryListMap();
    this.queryListEvent();
  }

  // 文件导入
  selectedFileOnChanged(event: any) {
    // 这里是文件选择完成后的操作处理
    this.uploader.queue[0].onSuccess = (response, status, headers) => {
      // 上传文件成功
      if (status === 200) {
        // 上传文件后获取服务器返回的数据
        const tempRes = JSON.parse(response);
        this.fileId = tempRes.systemFileTO.fileId;
        this.imgUrl = tempRes.systemFileTO.fileUrl;
      } else {
        // 上传文件后获取服务器返回的数据错误
      }
    };
    this.uploader.queue[0].upload(); // 开始上传
  }

// 增加逻辑
  onAddLo() {
    this.addLogicinfo(this.curaddLogicInfo)
      .then(
        page => {
          if (page) {
            this.alert.info('新增成功');
            setTimeout(() => {
              this.router.navigate(['/buz/logicAdmin']);
            }, 1500);
          }
        }
      );
  }

  addLogicinfo(addLogicInfo: AddLogicInfo): Promise<any> {
    const request = JSON.stringify({
      name: addLogicInfo.name,
      eventId: this.eventId,
      sort: addLogicInfo.sort,
      pathId: addLogicInfo.pathId,
      realNodeId: addLogicInfo.realNodeId,
      fileId: this.fileId
    });
    const requestBody = 'json=' + request;
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this.http
      .post(this.hostUrlAddLogic, requestBody, {headers: headers})
      .toPromise()
      .then(
        res => {
          const body = res.json();
          if (body.status === 1) {
            return true;
          } else if (body.status === 0) {
            this.alert.error(body.msg);
          } else if (body.status === 2) {
            this.alert.warn(body.msg);
          }
        }
      )
      .catch(this.handleError);
  }

  // 查询路径
  searchPath() {
    this.curPage = 1;
  }

  private queryListEvent() {
    this.logicAddService.getEvLofic(this.curPage)
      .then(page => {
          this.addEvent = page.addEvent.datas;
        }
      );
  }

  // 根据路径id查询路径
  queryListMapId() {
    this.logicAddService.getMapId(this.id)
      .then(
        res => {
          if (res[0]) {
            if (res[1].pathInfo.mapId !== '') {
              this.mapId = res[1].pathInfo.mapId;
              this.queryListR();
            }

          }
        }
      );
  }

  getPhysical() {
    if (this.mapId !== undefined) {
      this.queryListR();
    } else {
      alert('请先选择路径');
    }
  }

  queryListR() {
    this.logicAddService.getReal(this.curPage, this.mapId)
      .then(
        page => {
          if (page[0] = true) {
            this.realInfoPage = page[1];
          }
        }
      );
  }

  // 下拉路径id改变物理基点
  getP(Id: string) {
    this.id = Id;
    this.queryListMapId();
  }

// 查询Map
  queryListMap() {
    this.logicAddService.getMap()
      .then(
        res => {
          if (res[0]) {
            this.logic = res[1].mapTO;
          }
        }
      );
  }

// 选择路径前请选择地图
  selectPath() {
    if (this.map === undefined) {
      alert('请先选择地图');
    }
  }

  // 查询不同mapId对应不同的路径
  queryListPath(mapId: string) {
    this.map = mapId;
    this.logicAddService.getPath(this.curPage, this.map)
      .then(
        res => {
          if (res[0]) {
            this.path = res[1].datas;
          }
        }
      );
  }

  selEvent(id: string) {
    this.eventId = id;
  }

  private handleError(error: any): Promise<[boolean, any]> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject([false, error.toString()]);
  }
}
